<?php
namespace Api\Event;

/**
 * 内网请求
 */
class LocalClientEvent extends BaseEvent 
{
    /**
     * 请求service
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  string $type           请求类型
     * @param  array  $params         参数
     * @param  string $request_method 请求方式
     */
    public function doRequest($type, $params, $request_method = 'post') {
        $url = C("service.{$type}");
        if (!$url) {
            throw new \Exception('[LOCAL CLIENT] service error - '.$type);
        }
        $url = C('service.domain').$url;
        $response = http_request($url, $params, null, $request_method);
        \Think\Log::record("[SERVICE REQUEST:{$type}] - ".json_encode($params), 'DEBUG');
        \Think\Log::record("[SERVICE RESPONSE] - {$response}", 'DEBUG');
        $response = json_decode($response, true);
        return $response;
    }

    public function doAsyncRequest($type, $params, $request_method = 'post')
    {
        $url = C("service.{$type}");
        if (!$url) {
            throw new \Exception('[LOCAL CLIENT] service error - '.$type);
        }
        $url = C('service.domain').$url;
        http_request($url, $params, null, $request_method, true);
    }


    public function doRequestByJson($type, $params, $request_method = 'post')
    {
        $url = C("service.{$type}");
        if (!$url) {
            throw new \Exception('[LOCAL CLIENT] service error - '.$type);
        }
        $url = C('service.domain').$url;
        $response = http_request($url, json_encode($params), ['Content-Type:text/json'], $request_method);
        \Think\Log::record("[SERVICE REQUEST:{$type}] - ".json_encode($params), 'DEBUG');
        \Think\Log::record("[SERVICE RESPONSE] - {$response}", 'DEBUG');
        $response = json_decode($response, true);
        return $response;
    }
}